package mrHunter.data;

import mrHunter.MRInf;
import mrHunter.MRList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.simple.SimpleJdbcInsert;
import org.springframework.stereotype.Repository;

import java.util.*;

@Repository
public class JdbcMrRepository implements MrRepository{
    private JdbcTemplate jdbcTemplate;

    @Autowired
    public JdbcMrRepository(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    @Override
    public boolean save(MRInf mrInf) {
        SimpleJdbcInsert jdbcInsert = new SimpleJdbcInsert(jdbcTemplate).withTableName("mrinf");
        Map<String, Object> args = new HashMap<>();
        args.put("problemno",mrInf.getProblemNo());
        args.put("puzzleType",mrInf.getPuzzleType());
        args.put("username",mrInf.getUsername());
        args.put("mr1",mrInf.getMR1());
        args.put("mr2",mrInf.getMR2());
        args.put("result",mrInf.getResult());
        args.put("resultType",mrInf.getResultType());
        args.put("sourceInputNum",mrInf.getSourceInputNum());
        args.put("followupInputNum",mrInf.getFollowUpInputNum());
        args.put("time",mrInf.getTime());
        jdbcInsert.execute(args);
        return true;
    }

    @Override
    public MRList loadMrs() {
        List<MRInf> mrInfs=new ArrayList<>();

        List<Map<String,Object>> rows=jdbcTemplate.queryForList("select * from mrinf");
        for (Map row:rows){
            MRInf mrInf=new MRInf();
            mrInf.setTime((String)(row.get("time")));
            mrInf.setUsername((String)(row.get("username")));
            mrInf.setProblemNo((int)(row.get("problemNo")));
            mrInf.setProblemNo((int)(row.get("puzzleType")));
            mrInf.setResultType((String)(row.get("resultType")));
            mrInfs.add(mrInf);
        }
        return new MRList(mrInfs);
    }
}
